<template>
  <div class="app"></div>
</template>

<script>
import { defineComponent, ref, onMounted } from "vue";
export default defineComponent({
  name: "App",
});
</script>
<script setup>
import mqtt from "mqtt";

let mqttClient;

// mqtt 配置参数
const mqttConf = ref({
  host: "127.0.0.1",
  port: 1883,
  clientId: "mqttx_8f03e7e8",
});

// 连接 mqtt
const connectMqtt = () => {
  // 本地搭建的EXQX为 wx://xxx.xxx.xxx.xxx:xxxx/mqtt
  mqttClient = mqtt.connect("ws://127.0.0.1:8083/mqtt");

  // 监听连接成功消息
  mqttClient.on("connect", () => {
    console.log("连接成功");
    // 发起一个主题订阅
    subScribe("device_test_001");
  });

  // 监听失败消息
  mqttClient.on("error", (err) => {
    console.error("连接失败:", err);
  });

  // 接收主题消息
  mqttClient.on("message", (topic, message) => {
    console.log(`收到 ${topic} 消息：${message.toString()}`);
    console.log(JSON.parse(message.toString().replace(/\s/g, "")));
  });
};

// 订阅主题
const subScribe = (scribeName) => {
  mqttClient.subscribe(scribeName, { qos: 1 }, (err) => {
    if (err) {
      console.error("订阅失败:", err);
    } else {
      console.log("订阅成功");
    }
  });
};

onMounted(() => {
  connectMqtt();
});
</script>

<style scoped></style>
